package com.cloud.config;

import com.cloud.common.constants.GlobalConstants;
import com.cloud.common.enums.ServerTypeEnum;
import com.cloud.properties.RedissonConfigProperties;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author: ZhangKaiQiang
 * @date: 2021/4/15
 * @time: 17:41
 **/
public class RedissonConnectionManager {

    private Logger logger= LoggerFactory.getLogger(RedissonConnectionManager.class);

    /**
     * redis配置信息
     */
    private RedissonConfigProperties redissonConfigProperties;


    public RedissonConnectionManager(RedissonConfigProperties redissonConfigProperties){
        this.redissonConfigProperties=redissonConfigProperties;
    }


    /**
     * 获取RedissonClient
     * @return RedissonClient
     */
    public RedissonClient getRedissonClient(){
        String serverType = redissonConfigProperties.getServerType();
        if (StringUtils.isEmpty(serverType)){
            logger.info("RedissonClient 初始化时,配置文件中serverType字段不存在");
        }

        Config config = new Config();
        String address = redissonConfigProperties.getAddress();
        if (StringUtils.isEmpty(address)){
            address="127.0.0.1";
            logger.info("配置文件中address为null,使用127.0.0.1默认地址");
        }

        Integer dataBase = redissonConfigProperties.getDataBase();
        if(dataBase==null){
            dataBase=0;
        }

        if (ServerTypeEnum.Cluster.getCode().equalsIgnoreCase(serverType)){
           ClusterServersConfig clusterServersConfig = config.useClusterServers();
           String[] split = address.split(",");
           if (split.length>0){
               for (String oneAddress : split) {
                   clusterServersConfig.addNodeAddress(GlobalConstants.REDIS_CONNECTION_PREFIX+oneAddress);
               }
           }
           if (StringUtils.isEmpty(redissonConfigProperties.getPassword())){
               clusterServersConfig.setPassword(redissonConfigProperties.getPassword());
           }
           logger.info("RedissonClient使用集群模式初始化完成,address:{},password:{}",redissonConfigProperties.getAddress(),redissonConfigProperties.getPassword());
       } else if (ServerTypeEnum.Master.getCode().equalsIgnoreCase(serverType)){
           MasterSlaveServersConfig masterSlaveServersConfig = config.useMasterSlaveServers();
           if (StringUtils.isEmpty(redissonConfigProperties.getPassword())){
               masterSlaveServersConfig.setPassword(redissonConfigProperties.getPassword());
           }

           String[] split = address.split(",");
           if (split.length>0){
               masterSlaveServersConfig.setMasterAddress(GlobalConstants.REDIS_CONNECTION_PREFIX+split[0]);

               Set<String> slaveSet=new HashSet<>();
               for (int i = 1; i <split.length ; i++) {
                   slaveSet.add(GlobalConstants.REDIS_CONNECTION_PREFIX+split[i]);
               }
               masterSlaveServersConfig.setSlaveAddresses(slaveSet);
           }
           logger.info("RedissonClient使用主从模式初始化完成,address:{},password:{}",redissonConfigProperties.getAddress(),redissonConfigProperties.getPassword());
       } else if (ServerTypeEnum.Sentinel.getCode().equalsIgnoreCase(serverType)){
           SentinelServersConfig sentinelServersConfig = config.useSentinelServers();
           if (StringUtils.isEmpty(redissonConfigProperties.getPassword())){
               sentinelServersConfig.setPassword(redissonConfigProperties.getPassword());
           }
           sentinelServersConfig.setDatabase(dataBase);
           String[] split = address.split(",");
           if (split.length>0){
               sentinelServersConfig.setMasterName(split[0]);
               Arrays.stream(split).forEach(oneAddress->{
                   sentinelServersConfig.addSentinelAddress(GlobalConstants.REDIS_CONNECTION_PREFIX+oneAddress);
               });
           }
           logger.info("RedissonClient使用哨兵模式初始化完成,address:{},password:{}",redissonConfigProperties.getAddress(),redissonConfigProperties.getPassword());
       } else if (ServerTypeEnum.Replicated.getCode().equalsIgnoreCase(serverType)){
          throw  new RuntimeException("暂不支持Replicated模式");
       } else if (ServerTypeEnum.Single.getCode().equalsIgnoreCase(serverType)){
           SingleServerConfig singleServerConfig = config.useSingleServer();

           // 地址 数据库 密码等设置
           singleServerConfig.setAddress(GlobalConstants.REDIS_CONNECTION_PREFIX+redissonConfigProperties.getAddress());
           singleServerConfig.setDatabase(dataBase);
           if (StringUtils.isEmpty(redissonConfigProperties.getPassword())){
               singleServerConfig.setPassword(redissonConfigProperties.getPassword());
           }
           logger.info("RedissonClient使用单实例模式初始化完成,address:{},password:{}",redissonConfigProperties.getAddress(),redissonConfigProperties.getPassword());
       } else {
           logger.info("RedissonClient 初始化时,配置文件中serverType模式配置错误");
       }
        RedissonClient redissonClient = Redisson.create(config);
        return  redissonClient;
    }







}
